package cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 服务器端创建Cookie，保存到浏览器
 */
public class C1_CreateCookie extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("CreateCookie 被调用...");

        //1.创建一个Cookie对象
        /*
            I) username 该cookie的名字是唯一的，可以理解是成一个key
            II) lmy 该cookie的值
            III) 可以创建多个Cookie对象
            IV) 此时cookie在服务器端，还没有到浏览器
         */
        Cookie cookie = new Cookie("username", "lmy");
        Cookie cookie2 = new Cookie("email", "tom@sohu.com");

        resp.setContentType("text/html;charset=utf-8");
        //2.将cookie发送给浏览器，让浏览器将该cookie保存
        resp.addCookie(cookie);
        resp.addCookie(cookie2);
        PrintWriter writer = resp.getWriter();
        writer.println("<h1>创建cookie成功</h1>");
        writer.flush();
        writer.close();
    }
}
